package style.Leetcode.初级算法.linkedList.linkedList_20220820_1_合并两个有序的链表;

import style.Leetcode.初级算法.linkedList.ListNode;

/**
 * 合并两个有序链表
 * <p>
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * <p>
 * 输入：l1 = [], l2 = []
 * 输出：[]
 * <p>
 * 输入：l1 = [], l2 = [0]
 * 输出：[0]
 * <p>
 * 提示：
 * 两个链表的节点数目范围是 [0, 50]
 * -100 <= Node.val <= 100
 * l1 和 l2 均按 非递减顺序 排列 （递增）
 */
public class Solution {
    /**
     * 思路一： 非递归 todo
     */
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (null == list1) return list2;
        if (null == list2) return list1;

        ListNode dumy = new ListNode(0);
        ListNode curr = dumy;

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                curr.next = list1;
                list1 = list1.next;
            } else {
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }

        curr.next = list1 == null ? list2 : list1;
        return dumy.next;
    }

    /**
     * 思路二： 递归思路
     *
     */
    public ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;

        if (list1.val <= list2.val) {
            list1.next = mergeTwoLists2(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists2(list1, list2.next);
            return list2;
        }
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode list1 = new ListNode(1);
        list1.next = new ListNode(2);
        list1.next.next = new ListNode(3);
        list1.next.next.next = new ListNode(4);

        ListNode list2 = new ListNode(2);
        list2.next = new ListNode(3);
//        ListNode listNode1 = solution.mergeTwoLists1(list1, list2);
        ListNode listNode2 = solution.mergeTwoLists2(list1, list2);
        System.out.println(listNode2);

    }
}
